#-*-coding:utf-8-*-
# Create your views here.
from models import Projects,Project_course_info
from django.shortcuts import get_object_or_404, render_to_response
from django.template import loader, RequestContext
from django.http import HttpResponse,HttpResponseRedirect
from django.core.paginator import Paginator
import time,datetime


"""保存信息"""
def save (request):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    if request.method == 'POST':
            new_data = request.POST.copy()
            if new_data.has_key('id'):
                pj = Projects.objects.get(pk = new_data['id'])
                pj.name = new_data['name']
                pj.intro = new_data['intro']
                pj.imvalue=new_data['imvalue']
                #pj.position=new_data['position']
            else:
                pj = Projects(
                name = new_data['name'],
                intro = new_data['intro'],
                imvalue=new_data['imvalue'],
                #position=new_data['position'],
                )
            pj.save()
    return HttpResponseRedirect('/pjlist/')


"""Project列表"""
def list(request, page = '1'):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    pj = Projects.objects.order_by('id')
    paginator = Paginator(pj, 10)
    try:
        page = int(page)
#        page = int(request.GET.get('page','1'))
        fi = paginator.page(page)
    except:
        return HttpResponseRedirect('/pjlist', {'level':request.session['level']})

    return render_to_response('pjlist.html', {
    'paginator':paginator,
    'pj':fi.object_list,
    'is_paginated': paginator.num_pages > 1,
    'has_next': fi.has_next(),
    'has_previous': fi.has_previous(),
    'current_page': page,
    'next_page': page + 1,
    'previous_page': page - 1,
    'pages': paginator.num_pages,
    'page_numbers': range(paginator.num_pages + 1)[1:],
    'hits' : paginator.count,
    'level':request.session['level'],
    })

"""调用修改显示页"""
def edit(request, pj_id):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    pj = get_object_or_404(Projects, pk = pj_id)
    return render_to_response('edit_pj.html', {'pj': pj})


"""删除"""
def del_pj (request, pj_id = ""):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    Projects.objects.filter(pk = pj_id).delete()
    return HttpResponseRedirect('/pjlist/')


def retTime(date):
    if date:
        date = date.split('/')
        date = date[2]+'-'+date[1]+'-'+date[0]
    else:
        date = None
    
    return date


"""program information 项目课程记录"""
def p_information (request):
    pid=request.REQUEST.get('pid',"")
    p_obj=""
    if pid:
        p_obj = get_object_or_404(Projects, pk = int(pid))

    if request.method == 'POST':
            new_data = request.POST.copy()
            pp_obj = get_object_or_404(Projects, pk = int(new_data['program_id']))
            pinfo=Project_course_info(
            project=pp_obj,
            period=new_data['period'].strip(),
            modules=new_data['modules'].strip(),
            core_elective=request.POST.get('core_elective',''),
            coursecode=request.POST.get('coursecode',''),
            season=request.POST.get('season',''),
            year=new_data['year'].strip(),
            class_start=retTime(new_data['class_start'].strip()),
            class_end=retTime(new_data['class_end'].strip()),
            class_date3=retTime(request.POST.get('class_date3')),
            class_date4=retTime(request.POST.get('class_date4')),
            class_date5=retTime(request.POST.get('class_date5')),
            lecture=new_data['lecture'].strip(),
            textbook=new_data['textbook'].strip(),
            venue=new_data['venue'].strip(),
            attoch=new_data['attoch'].strip(),
            is_removed=0,
            )
            pinfo.save()
    today=datetime.date.today()
    today=str(today)
    pc_list=[]
    pcpass_list=[]
    pc_list_tmp=Project_course_info.objects.filter(project=p_obj,is_removed=0).order_by("-period")
    for pc in pc_list_tmp:
        pc.textbook = pc.textbook
        t_dict={}
        daystart=''
        try:
            day1=pc.class_start
            d_list=day1.split("/")
            daystart=d_list[2]+'-'+d_list[1]+'-'+d_list[0]
            #daystart = time.strptime(daystart,'%Y-%m-%d') 
            t_dict['day1']=daystart
        except:
            t_dict['day1']=''
        t_dict['per']=pc.period[-7:]
        t_dict['p']=pc
        if daystart>=today:
            t_dict.textbook = t_dict.textbook
            pc_list.append(t_dict)
        else:
            pcpass_list.append(t_dict)
    
    try:
        pc_list.sort(lambda x,y: cmp(x["day1"], y["day1"]))
    except:
        pass
    try:
        pcpass_list.sort(lambda x,y: cmp(y["day1"], x["day1"]))
    except:
        pass
    isnotsdf=''
    datecount=2
    if p_obj.id!=3 and p_obj.id!=17:
        isnotsdf='1'
    #UNCC MBA / Iowa MBA  要改为  输入4个日子
    #Stanford SELP 及 Stanford FE 要改为  输入5个日子
    if p_obj.id==3 or p_obj.id==17:
        datecount=5
    if p_obj.id==4 or p_obj.id==16:
        datecount=4


    p_list = Projects.objects.order_by('-position')
    return render_to_response('program/p_information.html',
        {'p_list': p_list,'p_obj':p_obj,'pc_list':pc_list,'pcpass_list':pcpass_list,'isnotsdf':isnotsdf,'datecount':datecount})

"""修改"""
def p_info_course_edit (request, pcid = ""):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    pid=request.REQUEST.get('pid',"")
    p_obj=""
    if pid:
        p_obj = get_object_or_404(Projects, pk = int(pid))
    pc_obj = get_object_or_404(Project_course_info, pk = int(pcid))
    if request.method == 'POST':
            new_data = request.POST.copy()
            
            pp_obj = get_object_or_404(Projects, pk = int(new_data['program_id']))
            pc_obj.project=pp_obj
            pc_obj.period=new_data['period'].strip()
            pc_obj.modules=new_data['modules'].strip()
            pc_obj.core_elective=request.POST.get('core_elective','')
            pc_obj.coursecode=request.POST.get('coursecode','')
            pc_obj.season=request.POST.get('season','')
            pc_obj.year=new_data['year'].strip()
            pc_obj.class_start=retTime(new_data['class_start'].strip())
            pc_obj.class_end=retTime(new_data['class_end'].strip())
            pc_obj.class_date3=retTime(request.POST.get('class_date3'))
            pc_obj.class_date4=retTime(request.POST.get('class_date4'))
            pc_obj.class_date5=retTime(request.POST.get('class_date5'))
            pc_obj.lecture=new_data['lecture'].strip()
            pc_obj.textbook=new_data['textbook'].strip()
            pc_obj.venue=new_data['venue'].strip()
            pc_obj.attoch=new_data['attoch'].strip()
            pc_obj.save()
            goback="/p_information/?pid="+str(pid)
            return HttpResponseRedirect(goback)
    p_list = Projects.objects.order_by('-position')
    isnotsdf=''
    datecount=2
    if p_obj.id!=3 and p_obj.id!=17:
        isnotsdf='1'
    #UNCC MBA / Iowa MBA  要改为  输入4个日子
    #Stanford SELP 及 Stanford FE 要改为  输入5个日子
    if p_obj.id==3 or p_obj.id==17:
        datecount=5
    if p_obj.id==4 or p_obj.id==16:
        datecount=4
    textbook = pc_obj.textbook

    return render_to_response('program/p_info_course_edit.html',
        {'p_list': p_list,'pc_obj':pc_obj,'p_obj':p_obj,'isnotsdf':isnotsdf,'datecount':datecount,'textbook':textbook})


"""删除"""
def p_info_course_del (request, pcid = ""):
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    p_obj = get_object_or_404(Project_course_info, pk = int(pcid))
    p_obj.is_removed=1
    p_obj.save()
    burl="/p_information/?pid="+str(p_obj.project.id)
    return HttpResponseRedirect(burl)